/**
 * 
 */
package com.ibuonline.search.solr.extend;

import java.io.IOException;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.Filter;
import org.apache.lucene.util.OpenBitSet;

/**
 * @author Liuye
 * 
 */
@SuppressWarnings("serial")
public class OnlineFilter extends Filter {
	public static final String NAME = "live_online";
	private static final String KEY = "userId";

	public OnlineFilter() {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.lucene.search.Filter#getDocIdSet(org.apache.lucene.index.
	 * IndexReader)
	 */
	@Override
	public DocIdSet getDocIdSet(IndexReader reader) throws IOException {
		List<Long> onlineUserIds = ExternalDataContext.getInstance()
				.getOnlineUserIds();
		if (onlineUserIds == null || onlineUserIds.isEmpty()) {
			return null;
		}
		OpenBitSet bitSet = new OpenBitSet(onlineUserIds.size());
		for (int i = 0; i < reader.maxDoc(); i++) {
			if (reader.isDeleted(i))
				continue;
			Document doc = reader.document(i);
			String userId = doc.get(KEY);
			if (StringUtils.isBlank(userId)) {
				continue;
			}
			if (!onlineUserIds.contains(Long.valueOf(userId))) {
				continue;
			}
			bitSet.fastSet(i);
		}
		return bitSet;
	}
}
